#!/bin/zsh

# 安装brew
if ! [ -x "$(command -v brew)" ]; then
    echo "您还没有安装brew,确定安装请按回车键"
    read key
    if [[ ${key} == `\\` ]]; then
        /bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"
    else
        exit 1
    fi
fi

# 安装NGINX
if ! [ -x "$(command -v nginx)" ]; then

    echo "您还没有安装nginx,确定安装请按回车键"

    if [[ ${key} == `\\` ]]; then
        brew install nginx
    else
        exit 1
    fi
fi

nginx_servers_path="/usr/local/etc/nginx/servers"
# 这里不能有空格
cat>${nginx_servers_path}/my.conf<<EOF
server {
    listen       8081;
    server_name  localhost;

    #charset koi8-r;
    charset utf-8;

    #access_log  logs/host.access.log  main;

    location / {
        root   /Users/admin/Downloads;
        #index  index.html index.htm;
        autoindex on;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}
EOF

nginx_process_num=$(ps -ef | grep nginx | grep -v grep | wc -l)
echo $nginx_process_num
# 判断进程是否存在，不存在就启动Nginx
if [ $nginx_process_num  -eq 2 ]; then
    # systemctl start nginx
    echo "NGINX没有启动"
    nginx
else
    echo "NGINX已经启动"
    nginx -s stop
    sleep 1
    nginx
fi
# nginx -t #检查配置是否正确
# nginx #启动
# nginx -s reload #重启
# nginx -s stop #停止
# brew services start nginx #后台启动
# /usr/local/etc/nginx/nginx.conf 配置文件所在的路径